package com.happok.onlineclass.usermanagement.authentication.config.handler;

import cn.hutool.json.JSONObject;
import com.happok.onlineclass.usermanagement.authentication.dto.LoginResultDTO;
import com.happok.onlineclass.usermanagement.authentication.service.AuthenticationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * [简要描述]: 自定义认证处理类
 * [详细描述]:
 *
 * @author:
 * @date: 5:08 PM 2019/10/17
 * @since: JDK 1.8
 */
@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private AuthenticationService authenticationService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String account = request.getParameter("account");
        LoginResultDTO loginResult = authenticationService.loginAccount(account);
        JSONObject jsonObject = new JSONObject(true);
        jsonObject.set("code", "20000");
        jsonObject.set("msg", "登录成功");
        jsonObject.set("data", loginResult);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(jsonObject.toString());
        response.flushBuffer();
    }
}
